﻿using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;
using System.Collections;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
namespace VSM
{
    public partial class ServiceRequest : System.Web.UI.Page
    {

 
        private static GeneralFunctions GF = null;

       
        private static string jobkind = "";
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session[Utils.AppConstants.ID_User] == null
                          || Session[Utils.AppConstants.Password] == null
                          || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../Login.aspx");
            }
            Response.Cache.SetCacheability(HttpCacheability.Private);
            if (!IsPostBack)
            {
                //dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                loadDropdownList();

                Session["ServiceID"] = Request.QueryString["ServiceID"] == null ? "-1" : Request.QueryString["ServiceID"];
                Session["ResID"] = Request.QueryString["ResID"] == null ? "-1" : Request.QueryString["ResID"];
                if (Session["ServiceID"].ToString() == "-1" && Session["ResID"].ToString() == "-1")
                {
                    generateNewJobID();
                    loadDefaultData();
                    createEmptyTable();
                }
                else if (Session["ServiceID"].ToString() != "-1")
                {
                    loadDataByServiceID();

                }else if(Session["ResID"].ToString() != "-1"){
                    generateNewJobID();
                    loadDefaultData();
                    loadDataByReservation();
                }
                
                // Add code check security here
                
                if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 0)
                {
                    //txtDealerCode.ReadOnly = true;
                    //txtDealerCode.BackColor = ColorTranslator.FromHtml("#E6E6E6");
                    //hf_GeneralID.Value = Request.QueryString["id"];
                    //btnUpdate.Text = "Update Dealer";
                    if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0)
                    {
                        
                    }
                }
                else if (string.Compare("VSM", (string)Session[Utils.AppConstants.ID_Dealer]) == 0) // Add new dealer
                {
                    //btnUpdate.Text = "Add Dealer";
                    //DealerCode.Value = "";
                }
            }
        }

        

        private void createEmptyTable()
        {
            DataTable dtTmp = new DataTable();
            dtTmp.Columns.Add("No");
            dtTmp.Columns.Add("DetailCode");
            dtTmp.Columns.Add("ItemCode");
            dtTmp.Columns.Add("ItemName");
            dtTmp.Columns.Add("FrgnName");
            dtTmp.Columns.Add("Quantity");
            dtTmp.Columns.Add("Price");
            dtTmp.Columns.Add("VAT");
            dtTmp.Columns.Add("DiscPrcnt");
            dtTmp.Columns.Add("Stock");

            Session["dtDetail"] = dtTmp;
            grvPO.DataSource = dtTmp;
            grvPO.DataBind();

        }
        private void generateNewJobID()
        {
            DateTime curr = DateTime.Now;
            
            Services sv = new Services();
            string sql = "select RIGHT('000' + CAST(count(*) + 1 as nvarchar(5)), 3) as GreatestNum from U_GeneralService where MONTH(ServiceDate) = "+ curr.Month.ToString() +" and YEAR(ServiceDate) = "+ curr.Year.ToString() +" and DealerCode = '" + Session[Utils.AppConstants.ID_Dealer].ToString() + "'";
            DataSet dsJobID = sv.ExecuteQuery("DEALER", sql);
            if (dsJobID.Tables[0].Rows.Count > 0) {
                
                txt_JobID.Text = dsJobID.Tables[0].Rows[0]["GreatestNum"].ToString() + "/" + curr.ToString("MMyy");
            }
            
        }

        private void loadDefaultData() {
            txt_Odometer.Text = "0";
            DateTime currDate = DateTime.Now;
            txtDate.Text = currDate.ToString("dd/MM/yyyy");

            txt_DateIn.Text = currDate.ToString("dd/MM/yyyy");
            txt_StartDate.Text = currDate.ToString("dd/MM/yyyy");

            Services svc = new Services();
            DataSet ds =  svc.ExecuteQuery("VSM", "select UserName from tbl_MasterUsers where ID_User = '" + Session[Utils.AppConstants.ID_User] + "'" );
            if (ds.Tables[0].Rows.Count > 0) {
                txt_Receptionist.Text = ds.Tables[0].Rows[0]["UserName"].ToString();
            }

            
        }

        private void loadDropdownList() {
            Services sv = new Services();

            DataSet dsJobkind = sv.ExecuteQuery("VSM", "select * from [@JOBKINDSVC] order by Code");
            ddl_JobKind.DataSource = dsJobkind.Tables[0];
            ddl_JobKind.DataTextField = "Name";
            ddl_JobKind.DataValueField = "Code";
            ddl_JobKind.DataBind();

            DataSet dsPayment = sv.ExecuteQuery("VSM", "select * from [@PAYMENTMETHODSVC] order by Code");
            ddl_Payment.DataSource = dsPayment.Tables[0];
            ddl_Payment.DataTextField = "Name";
            ddl_Payment.DataValueField = "Code";
            ddl_Payment.DataBind();

            DataSet dsAdviser = sv.ExecuteQuery("VSM", "select * from [@TECHNICIAN] where U_DealerCode = '" + Session[Utils.AppConstants.ID_Dealer] + "' order by Code ");
            ddl_Adviser.DataSource = dsAdviser.Tables[0];
            ddl_Adviser.DataTextField = "Name";
            ddl_Adviser.DataValueField = "Code";
            ddl_Adviser.DataBind();

            DataSet dsTech = sv.ExecuteQuery("VSM", "select * from [@TECHNICIAN] where U_DealerCode = '" + Session[Utils.AppConstants.ID_Dealer] + "' order by Code ");

            ddl_Technician.DataSource = dsTech.Tables[0];
            ddl_Technician.DataTextField = "Name";
            ddl_Technician.DataValueField = "Code";
            ddl_Technician.DataBind();

            DataSet dsDealer = sv.ExecuteQuery("VSM", "select CardCode, CardName from OCRD where CardCode = '" + Session[VSM.Utils.AppConstants.ID_Dealer] + "'");
            if (dsDealer.Tables[0].Rows.Count > 0) {
                hf_DealerName.Value = dsDealer.Tables[0].Rows[0]["CardName"].ToString();
            }

            DataSet dsModel = sv.ExecuteQuery("VSM", "Select -1 as ModelCode, 'Choose Mode' as ModelName  UNION ALL select ModelCode, ModelName from U_Model");
            ddl_Model.DataSource = dsModel.Tables[0];
            ddl_Model.DataTextField = "ModelName";
            ddl_Model.DataValueField = "ModelCode";
            ddl_Model.DataBind();

            DataSet dsPackage = sv.ExecuteQuery("VSM", "select -1 as PackageID, 'Choose Package' as PackageName Union All select PackageID, PackageName from U_Package");
            ddl_Package.DataSource = dsPackage.Tables[0];
            ddl_Package.DataTextField = "PackageName";
            ddl_Package.DataValueField = "PackageID";
            ddl_Package.DataBind();
        }

        private string FormatDate(string dateIn) {
            if (dateIn.Trim() == "")
                return "";
            DateTime pars = DateTime.Parse(dateIn);
            return pars.ToString("dd/MM/yyyy");
            
        }

        private void loadDataByReservation()
        {
            string sql = "SELECT [ResID],[SeqNo],[ServiceStaff],[ResDate],[ResTime],[DeliveryDate] ";

            sql += " ,[DeliveryTime],[ConfirmDate],[ConfirmTime],[CustomerCall],[EstimateCost] ";
            sql += " ,[PODate],[POTime],[PADate],[PATime],[CustomerRequest] ";
            sql += " ,[VehicleID],[VIN],[Brand],[VehicleName],[EngineNo] ";
            sql += " ,[RegNo],[Model],[ColorCode],[Odometer],[CustomerID] ";
            sql += " ,[CustomerName],[OtherName],[Address],[Tel],[Mobile] ";
            sql += " ,[TaxCode],[ContactPerson],[ContactPhone],[DealerCode] ";
            sql += "  FROM [Dealer_Test].[dbo].[U_Reservation] ";

            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataRow dr = ds.Tables[0].Rows[0];
                hf_CustomerCode.Value = dr["CustomerID"].ToString();
                hf_VehicleID.Value = dr["VehicleID"].ToString();

                txt_CustomerName.Text = dr["CustomerName"].ToString();
                txt_OtherName.Text = dr["OtherName"].ToString();
                txt_Address.Text = dr["Address"].ToString();
                txt_Tel.Text = dr["Tel"].ToString();
                txt_Mobile.Text = dr["Mobile"].ToString();
                txt_TaxCode.Text = dr["TaxCode"].ToString();
                txt_ContactPerson.Text = dr["ContactPerson"].ToString();
                txt_PhoneContact.Text = dr["ContactPhone"].ToString();

                txt_VIN.Text = dr["VIN"].ToString();
                txt_Brand.Text = dr["Brand"].ToString();
                txt_VehicleName.Text = dr["VehicleName"].ToString();
                txt_EngineNo.Text = dr["EngineNo"].ToString();
                txt_RegNo.Text = dr["RegNo"].ToString();
                txt_ColorCode.Text = dr["ColorCode"].ToString();
                txt_Model.Text = dr["Model"].ToString();

                txt_Odometer.Text = dr["Odometer"].ToString();

                string sqlDet = " SELECT ROW_NUMBER() OVER (ORDER BY DetailCode) AS No, * from U_ReservationDetail ";
                sqlDet += " where Status <> 1 AND ResID = " + Session["ResID"].ToString();
                DataSet dsDt = sv.ExecuteQuery("DEALER", sqlDet);
                Session["dtDetail"] = dsDt.Tables[0];
                grvPO.DataSource = dsDt.Tables[0];
                grvPO.DataBind();
                CalcTotal();

            }
        }

        private void loadDataByServiceID()
        {
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", "select * from U_GeneralService where GeneralID = " + Session["ServiceID"]);
            hf_GeneralID.Value = Session["ServiceID"].ToString();
            if (ds.Tables[0].Rows.Count > 0)
            {

                DataRow dr = ds.Tables[0].Rows[0];
                txtDate.Text = FormatDate(dr["ServiceDate"].ToString());
                txt_JobID.Text = dr["JobID"].ToString();
                txt_Receptionist.Text = dr["Receptionist"].ToString();

                if (ddl_Adviser.Items.FindByValue(dr["AdviserCode"].ToString()) != null)
                    ddl_Adviser.Items.FindByValue(dr["AdviserCode"].ToString()).Selected = true;
                if (ddl_Technician.Items.FindByValue(dr["TechnicianCode"].ToString()) != null)
                    ddl_Technician.Items.FindByValue(dr["TechnicianCode"].ToString()).Selected = true;

                jobkind = dr["JobKind"].ToString();
                ddl_JobKind.Items.FindByValue(dr["JobKind"].ToString()).Selected = true;
                ddl_Payment.Items.FindByValue(dr["Payment"].ToString()).Selected = true;
                txt_DateIn.Text = FormatDate(dr["DateIn"].ToString());
                txt_TimeIn.Text = dr["TimeIn"].ToString();
                txt_ExpDate.Text = FormatDate(dr["ExpDelivery"].ToString());
                txt_ExpTime.Text = dr["ExpTime"].ToString();
                txt_StartDate.Text = FormatDate(dr["StartDate"].ToString());
                txt_StartTime.Text = dr["StartTime"].ToString();
                txt_FinishDate.Text = FormatDate(dr["FinishDate"].ToString());
                txt_FinishTime.Text = dr["FinishTime"].ToString();
                txt_ActualDate.Text = FormatDate(dr["ActualDelivery"].ToString());
                txt_ActualTime.Text = dr["ActualDeliveryTime"].ToString();
                txt_CustomerRequest.Text = dr["CustomerRequest"].ToString();
                txt_Odometer.Text = dr["Odometer"].ToString();
                txt_Notice.Text = dr["Notice"].ToString();
                hf_CustomerCode.Value = dr["CustomerCode"].ToString();
                hf_VehicleID.Value = dr["VehicleCode"].ToString();

                txt_CustomerName.Text = dr["CustomerName"].ToString();
                txt_OtherName.Text = dr["OtherName"].ToString();
                txt_Address.Text = dr["Address"].ToString();
                txt_Tel.Text = dr["Tel"].ToString();
                txt_Mobile.Text = dr["Mobile"].ToString();
                txt_TaxCode.Text = dr["TaxCode"].ToString();
                txt_ContactPerson.Text = dr["ContactPerson"].ToString();
                txt_PhoneContact.Text = dr["ContactPhone"].ToString();

                txt_VIN.Text = dr["VIN"].ToString();
                txt_Brand.Text = dr["Brand"].ToString();
                txt_VehicleName.Text = dr["VehicleName"].ToString();
                txt_EngineNo.Text = dr["EngineNo"].ToString();
                txt_RegNo.Text = dr["RegNo"].ToString();
                txt_ColorCode.Text = dr["ColorCode"].ToString();
                txt_Model.Text = dr["Model"].ToString();

                loadDetail();

            }
        }
        private void loadCustomer() {
            MasterData masterDataWS = new MasterData();
            DataSet ds = masterDataWS.GetCustomerByCode("VSM", hf_CustomerCode.Value);
            if (ds.Tables[0].Rows.Count > 0)
            {
                txt_CustomerName.Text = ds.Tables[0].Rows[0]["CardName"].ToString();
                txt_OtherName.Text = ds.Tables[0].Rows[0]["CardFName"].ToString();
                txt_Address.Text = ds.Tables[0].Rows[0]["Address"].ToString();
                txt_Tel.Text = ds.Tables[0].Rows[0]["Phone1"].ToString();
                txt_TaxCode.Text = ds.Tables[0].Rows[0]["LicTradNum"].ToString();
                txt_ContactPerson.Text = ds.Tables[0].Rows[0]["U_ContactPerson"].ToString();
                txt_PhoneContact.Text = ds.Tables[0].Rows[0]["U_ContactPhone"].ToString();
            }
        }

        private void loadVehicle(string VIN) {
            Services sv = new Services();
            if (jobkind == "004")
            {
                string sql = "select  rn.DistNumber as VIN, rn.Notes as EngineNo, ms.Name as Model, ";
                sql += " cg.RegistrationNumber as RegNo, ";
                sql += " it.ItemName as VehicleName, rn.U_KeyNo as KeyNo, ms.Code as ModelCode, ";
                sql += " it.U_Color as ColorCode, rn.LotNumber as LotNo, it.UserText as Remarks, '' as Brand";

                sql += " from  OSRN rn ";
                sql += " join OITM it on it.ItemCode = rn.ItemCode ";
                sql += " join [@ModelSales] ms on ms.Code = it.U_ModelSales ";
                sql += " left join U_CustomerRegis cg on cg.VIN = rn.DistNumber ";
                sql += " where rn.DistNumber = '" + VIN + "' ";
                DataSet ds = sv.ExecuteQuery("VSM", sql);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                    txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                    txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();
                    txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
                    txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
                }
            }
            else
            {
                DataSet ds = sv.ExecuteQuery("DEALER", "select * from U_ServiceVehicle where VehicleID = " + hf_VehicleID.Value);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    txt_VIN.Text = ds.Tables[0].Rows[0]["VIN"].ToString();
                    txt_EngineNo.Text = ds.Tables[0].Rows[0]["EngineNo"].ToString();
                    txt_RegNo.Text = ds.Tables[0].Rows[0]["RegNo"].ToString();
                    txt_ColorCode.Text = ds.Tables[0].Rows[0]["ColorCode"].ToString();
                    txt_Model.Text = ds.Tables[0].Rows[0]["Model"].ToString();
                }
            }
        }

        private void loadDetail() {
            Services sv = new Services();
            DataSet ds = sv.ExecuteQuery("DEALER", " SELECT ROW_NUMBER() OVER (ORDER BY DetailCode) AS No, * from U_GeneralServiceDetail where Status <> 1 AND GeneralID = " + Session["ServiceID"]);
            Session["dtDetail"] = ds.Tables[0];
            grvPO.DataSource = ds.Tables[0];
            grvPO.DataBind();
            CalcTotal();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            if (tblData.Rows.Count > 0)
            {
                DataRow dr = tblData.Rows[0];
                //txtDealerCode.Text = dr["CardCode"].ToString();
                //txtDealerName.Text = dr["CardName"].ToString();
                //txtAddress.Text = dr["Address"].ToString();
                //txtTaxCode.Text = dr["LicTradNum"].ToString();
                //txtTel1.Text = dr["Phone1"].ToString();
                //txtTel2.Text = dr["Phone2"].ToString();
                //txtMobilePhone.Text = dr["Cellular"].ToString();
                //txtEmail.Text = dr["E_mail"].ToString();
                //txtFax.Text = dr["Fax"].ToString();
            }
            if (fu_ImportExcel.HasFile) { 
                
            }
        }

        protected void btn_New_Click(object sender, EventArgs e)
        {
          
            //txtPONo.Text = "PO-" + "003/0414";
            //txtDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
      
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            //if (txtDealerCode.Text == "")
            //{
            //    Session["errorMessage"] = "Missing Dealer Code";
            //    Session["requestXML"] = "";
            //    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Dealer Code','');", true);
            //}
            /*
            String requestXML = _collectData();
            Transaction ts = new Transaction();

            DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.BUSINESS_PARTNER).ToString(), txtDealerCode.Text, !string.IsNullOrEmpty(DealerCode.Value), Utils.AppConstants.VSM
            );

            if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
            {
                Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                Session["requestXML"] = requestXML;
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
            }
            else
            {
                Session["successMessage"] = "Operation complete sucessful!";
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
            }
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
       
             */
        }
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
               // Utils.AppConstants.ConvertToDate(this.txtPODate.Text.Trim());
               // this.btnShowPopup.Enabled = true;
            }
            catch
            {
                //this.btnShowPopup.Enabled = false;
            }
            //UpdatePrice();
        }
        
 
        /// <summary>
        /// 
        /// </summary>
        private void ResetPage()
        {

            /*this.txtVendorCode.Text = "";
            this.txtVendorName.Text = "";
            this.Session["ChosenItem"] = null;
            this.Session["ChosenVendorCode"] = null;
            this.Session["ChosenVendorName"] = null;
            Session["SODATA"] = null;
            LoadOrderWareHouse();
            LoadData();
            this.btnUpdate.Enabled = false;*/
        }

       
      
        protected void TextBox_Change(object sender, EventArgs e)
        {
            // string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

            TextBox tb = (TextBox)sender;
            string ItemCode = tb.Text;
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lb_No");
            int rowNo = Int32.Parse( lblNo.Text) -1;
            int index = 0;
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            foreach (DataRow dr in dtTmp.Rows)
            {
                if (rowNo == index) {

                    MasterData mt = new MasterData();

                    //DataSet dsItem = mt.GetItemsByItemCodeList("VSM", Utils.AppConstants.ID_Dealer, ItemCode);
                    DataRow drNew = GetLineInfo(ItemCode, 1);

                    if (drNew != null)
                    {

                        dr["ItemCode"] = ItemCode;
                        dr["ItemName"] = drNew["ItemName"];
                        dr["FrgnName"] = drNew["FrgnName"];
                        dr["Quantity"] = 1;
                        dr["Price"] = drNew["Price"];
                        dr["VAT"] = drNew["VAT"];
                        dr["DiscPrcnt"] = drNew["DiscPrcnt"];
                        dr["Stock"] = 0;

                        Session["dtDetail"] = dtTmp;
                        grvPO.DataSource = dtTmp;
                        grvPO.DataBind();
                        CalcTotal();
                        this.lblError.Visible = false;
                        break;
                    }
                    //else if (dsItem.Tables[0].Rows.Count > 1)
                    //{
                    //    string msg = "Available parts: ";
                    //    foreach (DataRow drItem in dsItem.Tables[0].Rows)
                    //    {
                    //        msg += "";
                    //    }
                    //    this.lblError.Text = msg;
                    //    this.lblError.Visible = true;
                    //    break;
                    //}
                    else { //=0
                        this.lblError.Text = "There is no part with code [" + tb.Text + "] available ";
                        this.lblError.Visible = true;
                    }
                    
                }
                index++;
            }
        }

        protected void btn_AddMultiItems_Click(object sender, EventArgs e)
        {
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            DataRow dr = dtTmp.NewRow();
            dr["No"] = dtTmp.Rows.Count + 1;
            dr["DetailCode"] = -1;
            dr["ItemCode"] = "";
            dr["ItemName"] = "";
            dr["FrgnName"] = "";
            dr["Quantity"] = 1;
            dr["Price"] = 0;
            dr["VAT"] = 10;
            dr["DiscPrcnt"] = 10;
            dr["Stock"] = 0;

            dtTmp.Rows.Add(dr);
            this.grvPO.DataSource = dtTmp;
            this.grvPO.DataBind();
            Session["dtDetail"] = dtTmp;
        }

        //RUKOWEN ADDED
        protected void grvPO_RowCreated(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    GridViewRow myRow = e.Row;
            //    Label lblNo = myRow.FindControl("lblNo") as Label;
            //    lblNo.Text = (myRow.RowIndex + 1).ToString();
            //    //if (this.hdnStatus.Value == "C")
            //    //{
            //    //    TextBox txtQuantity = myRow.FindControl("txtOrderQuantity") as TextBox;
            //    //    txtQuantity.Enabled = false;
            //    //}
            //}
        }

        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvPO.PageIndex = e.NewPageIndex;
            DataTable tblPOR1 = (DataTable)Session["POR1Table"];
            BindData(tblPOR1);
        }

        private void CalcTotal()
        {
            try
            {

                DataTable dtTmp = (DataTable)Session["dtDetail"];
                
                double subTotal = 0;
                double vatAmount = 0;
                double discountAmount = 0;
                double grandTotal = 0;
                foreach (DataRow row in dtTmp.Rows)
                {
                    double qty = Double.Parse(row["Quantity"].ToString());
                    double price = Double.Parse(row["Price"].ToString());
                    double lineTotal = qty * price;
                    subTotal += lineTotal;

                    if (row["VAT"] != null && row["VAT"].ToString().Length > 0)
                    {
                        double vatPercent = double.Parse(row["VAT"].ToString());
                        vatAmount += (vatPercent / 100) * lineTotal;
                    }
                    if (row["DiscPrcnt"] != null && row["DiscPrcnt"].ToString().Length > 0)
                    {
                        double discountLine = double.Parse(row["DiscPrcnt"].ToString());
                        discountAmount += (discountLine / 100) * lineTotal;
                    }
                }
                grandTotal = subTotal + vatAmount - discountAmount;
                lb_SubTotal.Text = string.Format("{0:C}", Math.Round(subTotal, 2));
                lb_VATAmount.Text = string.Format("{0:C}", Math.Round(vatAmount, 2));
                lb_DiscountAmt.Text = string.Format("{0:C}", Math.Round(discountAmount, 2));
                lb_GrandTotal.Text = string.Format("{0:C}", Math.Round(grandTotal, 2));
                
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            /*
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                int index = 0;
                TextBox ddl1 = e.Row.FindControl("txtOrderQuantity") as TextBox;
                ddl1.Attributes.Add("onfocus", "JavaScript:document.getElementById('" + ddl1.ClientID + "').select();");
                if (ViewState["rowindex"] != null && Session["POTable"] != null)
                {
                    index = Convert.ToInt32(ViewState["rowindex"].ToString());
                    int rowCount = ((DataTable)Session["POTable"]).Rows.Count;
                    if ((index + 1) <= this.grvPO.Rows.Count)
                    {
                        if (e.Row.RowIndex == index + 1)
                        {
                            ddl1.Focus();
                            //ScriptManager.GetCurrent(this).SetFocus(ddl1.ClientID);
                        }
                    }
                }
            }
             * */
        }

        private void saveGrid()
        {
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            dtTmp.Rows.Clear();

            foreach (GridViewRow row in grvPO.Rows)
            {
                DataRow newRow = dtTmp.NewRow();
                newRow["No"] = ((Label)row.FindControl("lb_No")).Text;
                newRow["DetailCode"] = ((Label)row.FindControl("lb_DetailCode")).Text;
                newRow["ItemCode"] = ((TextBox)row.FindControl("txt_ItemCode")).Text;
                newRow["ItemName"] = ((Label)row.FindControl("lb_ItemName")).Text;

                newRow["FrgnName"] = ((Label)row.FindControl("lb_FrgnName")).Text;
                newRow["Quantity"] = ((TextBox)row.FindControl("txt_Qty")).Text;
                newRow["Price"] = ((Label)row.FindControl("lb_Price")).Text;
                newRow["VAT"] = ((Label)row.FindControl("lb_VAT")).Text;
                newRow["DiscPrcnt"] = ((TextBox)row.FindControl("txt_DiscPrcnt")).Text;
                newRow["Stock"] = ((Label)row.FindControl("lb_Stock")).Text;
                dtTmp.Rows.Add(newRow);
            }

            Session["dtDetail"] = dtTmp;
        }

        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                saveGrid();
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lb_No");
                int rowNo = Int32.Parse(lblNo.Text);
                DataTable dtTmp = (DataTable)Session["dtDetail"];
                Services sv = new Services();
                foreach (DataRow dr in dtTmp.Rows)
                {
                    if (rowNo == Int32.Parse(dr["No"].ToString()))
                    {
                        string DetID = dr["DetailCode"].ToString();
                        if (DetID != "-1")
                        {
                            DataSet dsDel = new DataSet();
                            DataTable dtDel = new DataTable();
                            dtDel.Columns.Add("DetailCode");
                            DataRow drDel = dtDel.NewRow();
                            drDel["DetailCode"] = DetID;

                            dtDel.Rows.Add(drDel);
                            dsDel.Tables.Add(dtDel);

                            sv.DeleteGeneralServiceDetail("DEALER", dsDel);
                        }
                        dr.Delete();
                        break;
                    }
                }
                //reset number
                dtTmp.AcceptChanges();
                int index = 0;
                foreach (DataRow dr in dtTmp.Rows)
                    dr["No"] = ++index;

                Session["dtDetail"] = dtTmp;
                grvPO.DataSource = dtTmp;
                grvPO.DataBind();
                CalcTotal();
            }
            catch (Exception ex)
            {
                //this.lblError.Text = ex.Message;
                //this.lblError.Visible = true;
            }
        }

        public void updateRowTotalPrice(DataRow row, string currColName)
        {
            double quantity = 0, unitPrice = 0.0, discount = 0, priceAfterDiscount = 0.0, total = 0;
            quantity = GF.Object2Double(GF.ResetFormatNumeric(row["Quantity"].ToString()), "QtyDec");
            unitPrice = GF.Object2Double(GF.ResetFormatNumeric(row["PriceBefDi"].ToString()), "PriceDec");
            discount = GF.Object2Double(GF.ResetFormatNumeric(row["DiscPrcnt"].ToString()), "PercentDec");
            priceAfterDiscount = GF.Object2Double((Object)(unitPrice * (100 - discount) / 100), "PriceDec");

            total = GF.Object2Double((Object)(priceAfterDiscount * quantity), "SumDec");

            if (string.IsNullOrEmpty(currColName))
                row["Quantity"] = GF.FormatNumeric(quantity.ToString(), "QtyDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt"))
                row["PriceBefDi"] = GF.FormatNumeric(unitPrice.ToString(), "PriceDec");
            if (string.IsNullOrEmpty(currColName) || currColName.Equals("PriceBefDi") || currColName.Equals("DiscPrcnt") || currColName.Equals("Quantity"))
                row["DiscPrcnt"] = GF.FormatNumeric(discount.ToString(), "PercentDec");

            row["Price"] = GF.FormatNumeric(priceAfterDiscount.ToString(), "PriceDec");
            row["LineTotal"] = GF.FormatNumeric(total.ToString(), "SumDec");

        }

        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            TextBox tb = (TextBox)sender;
            string ItemCode = tb.Text;
            GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
            Label lblNo = (Label)row.FindControl("lb_No");
            int rowNo = Int32.Parse(lblNo.Text) - 1;
            int index = 0;
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            foreach (DataRow dr in dtTmp.Rows)
            {
                if (rowNo == index)
                {

                    TextBox txtQty = (TextBox)row.FindControl("txt_Qty");
                    dr["Quantity"] = txtQty.Text;
                    dtTmp.AcceptChanges();
                    Session["dtDetail"] = dtTmp;
                    grvPO.DataSource = dtTmp;
                    grvPO.DataBind();
                    CalcTotal();
                    break;
                }
                index++;
            }
        }

        protected void txt_Discount_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                TextBox tb = (TextBox)sender;
                string ItemCode = tb.Text;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                Label lblNo = (Label)row.FindControl("lb_No");
                int rowNo = Int32.Parse(lblNo.Text) - 1;
                int index = 0;
                DataTable dtTmp = (DataTable)Session["dtDetail"];
                foreach (DataRow dr in dtTmp.Rows)
                {
                    if (rowNo == index)
                    {

                        TextBox txtDiscount = (TextBox)row.FindControl("txt_DiscPrcnt");
                        dr["DiscPrcnt"] = txtDiscount.Text;
                        dtTmp.AcceptChanges();
                        Session["dtDetail"] = dtTmp;
                        grvPO.DataSource = dtTmp;
                        grvPO.DataBind();
                        CalcTotal();
                        break;
                    }
                    index++;
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvPO.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["POR1Table"]);
        }

        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvPO.EditIndex = -1;
            BindData((DataTable)Session["POR1Table"]);
        }

        private void GetPrice(DataRow r)
        {
            try
            {
                /*
                DataSet ds = GetDataItem(DateTime.Parse(this.txtPODate.Text.Trim()), r["ItemCode"].ToString(), this.txtVendorCode.Text, double.Parse(r["Quantity"].ToString()));
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    if (ds.Tables[0].Rows[0]["BuyUnitMsr"].ToString().ToUpper() == "CTN")
                    {
                        r["Price"] = (decimal.Parse(ds.Tables[0].Rows[0]["NumInBuy"].ToString()) * decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    else
                    {
                        r["Price"] = decimal.Parse(ds.Tables[0].Rows[0]["Price"].ToString()).ToString(Utils.AppConstants.NUMBER_FORMAT);
                    }
                    r["LineTotal"] = (double.Parse(r["Price"].ToString()) * double.Parse(r["Quantity"].ToString())).ToString(Utils.AppConstants.NUMBER_FORMAT);
                }
                 * */
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }

        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tb.Rows.Remove(rupdate[0]);
                    }
                    this.grvPO.EditIndex = -1;
                    BindData((DataTable)Session["POR1Table"]);
                    CalcTotal();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = (GridViewRow)this.grvPO.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;
                        GetPrice(rupdate[0]);
                    }

                    this.grvPO.EditIndex = -1;

                    BindData(tb);
                    CalcTotal();
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void txtDiscPrcnt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtDiscPrcnt = (TextBox)row.FindControl("txtDiscPrcnt");
                if (txtDiscPrcnt.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtDiscPrcnt.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tb = (DataTable)Session["POR1Table"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DiscPrcnt"] = txtDiscPrcnt.Text;
                        updateRowTotalPrice(rupdate[0], "DiscPrcnt");
                    }
                }

                this.grvPO.EditIndex = -1;

                BindData(tb);
                CalcTotal();
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btn_ImportPackage_Click(object sender, EventArgs e)
        {
            string selectedModel = ddl_Model.SelectedValue.ToString();
            string selectedPackage = ddl_Package.SelectedValue.ToString();
            if (selectedModel != "-1")
            {
                if (selectedPackage != "-1")
                {
                    Services sv = new Services();
                    string sql = "select PacDetID, ItemCode, Quantity from  U_PackageDetail where PackageID = " + selectedPackage + " AND ModelCode = " + selectedModel;
                    DataSet ds = sv.ExecuteQuery("VSM", sql);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        DataTable dtTmp = (DataTable)Session["dtDetail"];
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            string ItemCode = dr["ItemCode"].ToString();
                            double qty = Double.Parse(dr["Quantity"].ToString());
                            dtTmp.Rows.Add(GetLineInfo(ItemCode, qty));
                        }
                        grvPO.DataSource = dtTmp;
                        grvPO.DataBind();
                        Session["dtDetail"] = dtTmp;
                        CalcTotal();
                    }
                }
            }

        }


        private DataRow GetLineInfo(string ItemCode, double qty)
        {
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            DataRow dr = dtTmp.NewRow();
            GetDefault defaultWS = new GetDefault();
            MasterData mt = new MasterData();
            DataSet dsItem = mt.GetItemsByItemCodeList("VSM", Session[Utils.AppConstants.ID_Dealer].ToString(), "'"+ItemCode+"'");

            DataSet defaultInfo = defaultWS.GetPartsDefaultLineInfo("VSM", Session[Utils.AppConstants.ID_Dealer].ToString(),
                Session[Utils.AppConstants.ID_Dealer].ToString(), ItemCode, qty, DateTime.Now, Session[Utils.AppConstants.U_Department].ToString(), "4");
           
            dr["DetailCode"] = -1;
            dr["No"] = dtTmp.Rows.Count + 1;
            dr["ItemCode"] = ItemCode;
            dr["ItemName"] = dsItem.Tables[0].Rows[0]["ItemName"];
            dr["FrgnName"] = dsItem.Tables[0].Rows[0]["FrgnName"];
            dr["Quantity"] = qty;
            dr["Price"] = defaultInfo.Tables[0].Rows[0]["UnitPrice"];
            dr["VAT"] = defaultInfo.Tables[0].Rows[0]["TaxRate"]; ;
            dr["DiscPrcnt"] = defaultInfo.Tables[0].Rows[0]["Discount"];
            dr["Stock"] = 0; //dsItem.Tables[0].Rows[0]["Stock"];

            return dr;
        }

        protected void btn_Save_Click(object sender, EventArgs e)
        {
            saveGrid();
            DataTable dt = new DataTable();
            dt.Columns.Add("ServiceDate");
            dt.Columns.Add("JobID");
            dt.Columns.Add("Receptionist");
            dt.Columns.Add("AdviserCode");
            dt.Columns.Add("TechnicianCode");
            dt.Columns.Add("JobKind");
            dt.Columns.Add("Payment");
            dt.Columns.Add("DateIn");
            dt.Columns.Add("TimeIn");
            dt.Columns.Add("ExpDelivery");
            dt.Columns.Add("ExpTime");
            dt.Columns.Add("StartDate");
            dt.Columns.Add("StartTime");
            dt.Columns.Add("FinishDate");
            dt.Columns.Add("FinishTime");
            dt.Columns.Add("ActualDelivery");
            dt.Columns.Add("ActualDeliveryTime");
            dt.Columns.Add("CustomerRequest");
            dt.Columns.Add("Notice");
            dt.Columns.Add("CustomerCode");
            dt.Columns.Add("VehicleCode");

            dt.Columns.Add("Odometer");
            dt.Columns.Add("DealerCode");
            dt.Columns.Add("GeneralID");

            dt.Columns.Add("VIN");
            dt.Columns.Add("Brand");
            dt.Columns.Add("VehicleName");
            dt.Columns.Add("EngineNo");
            dt.Columns.Add("RegNo");
            dt.Columns.Add("Model");
            dt.Columns.Add("ColorCode");

            dt.Columns.Add("CustomerName");
            dt.Columns.Add("OtherName");
            dt.Columns.Add("Address");
            dt.Columns.Add("Tel");
            dt.Columns.Add("Mobile");
            dt.Columns.Add("TaxCode");
            dt.Columns.Add("ContactPerson");
            dt.Columns.Add("ContactPhone");
            dt.Columns.Add("DealerName");

            DataRow dr = dt.NewRow();
            if (txtDate.Text.Trim() == "")
                dr["ServiceDate"] = DBNull.Value;
            else
                dr["ServiceDate"] = Utils.AppConstants.ConvertToDate(txtDate.Text.Trim());

            dr["JobID"] = txt_JobID.Text;
            dr["Receptionist"] = txt_Receptionist.Text;
            dr["AdviserCode"] = ddl_Adviser.SelectedValue;
            dr["TechnicianCode"] = ddl_Technician.SelectedValue;
            dr["JobKind"] = ddl_JobKind.SelectedValue;
            dr["Payment"] = ddl_Payment.SelectedValue;
            if (txt_DateIn.Text.Trim() == "")
                dr["DateIn"] = DBNull.Value;
            else
                dr["DateIn"] = Utils.AppConstants.ConvertToDate(txt_DateIn.Text.Trim());

            dr["TimeIn"] = txt_TimeIn.Text;
            if (txt_ExpDate.Text.Trim() == "")
                dr["ExpDelivery"] = DBNull.Value;
            else
                dr["ExpDelivery"] = Utils.AppConstants.ConvertToDate(txt_ExpDate.Text.Trim());

            dr["ExpTime"] = txt_ExpTime.Text;
            if (txt_StartDate.Text.Trim() == "")
                dr["StartDate"] = DBNull.Value;
            else
                dr["StartDate"] = Utils.AppConstants.ConvertToDate(txt_StartDate.Text.Trim());
            dr["StartTime"] = txt_StartTime.Text;

            if (txt_FinishDate.Text.Trim() == "")
                dr["FinishDate"] = DBNull.Value;
            else
                dr["FinishDate"] = Utils.AppConstants.ConvertToDate(txt_FinishDate.Text.Trim());
            dr["FinishTime"] = txt_FinishTime.Text;

            if (txt_ActualDate.Text.Trim() == "")
                dr["ActualDelivery"] = DBNull.Value;
            else
                dr["ActualDelivery"] = Utils.AppConstants.ConvertToDate(txt_ActualDate.Text.Trim());
            dr["ActualDeliveryTime"] = txt_ActualTime.Text;
            dr["CustomerRequest"] = txt_CustomerRequest.Text;
            dr["Notice"] = txt_Notice.Text;
            dr["CustomerCode"] = hf_CustomerCode.Value;
            dr["VehicleCode"] = hf_VehicleID.Value;
            dr["Odometer"] = txt_Odometer.Text;
            dr["DealerCode"] = Session[Utils.AppConstants.ID_Dealer].ToString();
            dr["GeneralID"] = Session["ServiceID"].ToString();
            dr["VIN"] = txt_VIN.Text;

            dr["Brand"] = txt_Brand.Text;
            dr["VehicleName"] = txt_VehicleName.Text;
            dr["EngineNo"] = txt_EngineNo.Text;
            dr["RegNo"] = txt_RegNo.Text;
            dr["Model"] = txt_Model.Text;
            dr["ColorCode"] = txt_ColorCode.Text;

            dr["CustomerName"] = txt_CustomerName.Text;
            dr["OtherName"] = txt_OtherName.Text;
            dr["Address"] = txt_Address.Text;
            dr["Tel"] = txt_Tel.Text;
            dr["Mobile"] = txt_Mobile.Text;
            dr["TaxCode"] = txt_TaxCode.Text;
            dr["ContactPerson"] = txt_ContactPerson.Text;
            dr["ContactPhone"]= txt_PhoneContact.Text;
            dr["DealerName"] = hf_DealerName.Value;


            Services svc = new Services();
            dt.Rows.Add(dr);
            DataSet ds = new DataSet();
            ds.Tables.Add(dt);

            if (Session["ServiceID"].ToString() == "-1") //add new
            {
               
                int ServiceID = svc.InsertGeneralService("DEALER", ds);
                
                if (ServiceID != -1)
                {
                    hf_GeneralID.Value = ServiceID.ToString();
                    Session["ServiceID"] = ServiceID.ToString();
                    InsertUpdateDetail();
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "[Add New] Operation complete sucessful!" + "','');", true);
                   
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "[Add New] ! Operation Failed" + "','');", true);
                }
            }
            else { //update
                int count = svc.UpdateGeneralService("DEALER", ds);
                if (count != -1)
                {
                    InsertUpdateDetail();
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "[Update] Operation complete sucessful!" + "','');", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "[Update] Operation failed!" + "','');", true);
                }
            }

        }

        private void InsertUpdateDetail() {
            DataSet dsDetail = new DataSet();
            DataTable dtDetail = new DataTable();
            dtDetail.Columns.Add("DetailCode");
            dtDetail.Columns.Add("GeneralID");
            dtDetail.Columns.Add("ItemCode");
            dtDetail.Columns.Add("ItemName");
            dtDetail.Columns.Add("FrgnName");
            dtDetail.Columns.Add("Quantity");
            dtDetail.Columns.Add("Price");
            dtDetail.Columns.Add("VAT");
            dtDetail.Columns.Add("DiscPrcnt");
            dtDetail.Columns.Add("Stock");
            Services svc = new Services();
            DataTable dtTmp = (DataTable)Session["dtDetail"];
            foreach (DataRow drDetail in dtTmp.Rows)
            {
                dsDetail.Tables.Clear();
                DataRow toAdd = dtDetail.NewRow();

                toAdd["DetailCode"] = drDetail["DetailCode"];
                toAdd["GeneralID"] = Session["ServiceID"].ToString();
                toAdd["ItemCode"] = drDetail["ItemCode"];
                toAdd["ItemName"] = drDetail["ItemName"];
                toAdd["FrgnName"] = drDetail["FrgnName"];
                toAdd["Quantity"] = drDetail["Quantity"];
                toAdd["Price"] = drDetail["Price"];
                toAdd["VAT"] = drDetail["VAT"];
                toAdd["DiscPrcnt"] = drDetail["DiscPrcnt"];
                toAdd["Stock"] = drDetail["Stock"];
                dtDetail.Rows.Clear();
                dtDetail.Rows.Add(toAdd);
                dsDetail.Tables.Add(dtDetail);
                if (drDetail["DetailCode"].ToString() == "-1")
                    svc.InsertGeneralServiceDetail("DEALER", dsDetail);
                else
                    svc.UpdateGeneralServiceDetail("DEALER", dsDetail);

            }
            loadDetail();
        }

        protected void btn_ImportExcel_Click(object sender, EventArgs e)
        {
            /*
            if (fu_ImportExcel.HasFile)
            {
                string FileName = Path.GetFileName(fu_ImportExcel.PostedFile.FileName);
                string Extension = Path.GetExtension(fu_ImportExcel.PostedFile.FileName);
                string FolderPath = "ExcelTmpFile";

                string FilePath = Server.MapPath(Path.Combine(FolderPath, FileName));
                fu_ImportExcel.SaveAs(FilePath);


                HSSFWorkbook hssfwb;
                using (FileStream file = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                {
                    hssfwb = new HSSFWorkbook(file);

                }

                Sheet sheet = hssfwb.GetSheet("Sheet1");
                for (int row = 1; row <= sheet.LastRowNum; row++)
                {
                    if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
                    {
                        string ItemCode = sheet.GetRow(row).GetCell(2).StringCellValue;
                        double qty = sheet.GetRow(row).GetCell(4).NumericCellValue;

                        if (ItemCode.Trim() != "")
                        {

                            dtContents.Rows.Add(GetLineInfo(ItemCode, qty));
                        }
                    }
                }
                grvPO.DataSource = dtContents;
                grvPO.DataBind();
            }
             * */
        }

        protected void btn_TechnicalDoc_Click(object sender, EventArgs e)
        {
            //string filePath = Server.MapPath("Technical");

            string fileName = "Igor.pdf";
            string popup = "OpenTechnicalDocument('" + fileName + "')";
            ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
            
        }
    }

}